package sb.de.advanceShopper.dataBase;

import java.util.ArrayList;
import java.util.List;

import sb.de.advanceShopper.controller.GPS;
import sb.de.advanceShopper.model.City;
import sb.de.advanceShopper.model.Shop;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ShopsDataSource {

	private SQLiteDatabase database;

	private ShopsSQLiteHelper dbHelper;

	private String[] allColumns = { ShopsSQLiteHelper.SHOPS_TCID,
			ShopsSQLiteHelper.SHOPS_TCNAME, ShopsSQLiteHelper.SHOPS_TCCITY,
			ShopsSQLiteHelper.SHOPS_TCLATITUDE, ShopsSQLiteHelper.SHOPS_TCLONGITUDE,
			ShopsSQLiteHelper.SHOPS_TCDESCRIPTION };

	public ShopsDataSource(Context context) {
		dbHelper = new ShopsSQLiteHelper(context);
	}

	private void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	private void close() {
		dbHelper.close();
	}

	public Shop createShop(String name, City city, String description) {
		open();
		
		Shop res;
		ContentValues values = new ContentValues();		
		values.put(ShopsSQLiteHelper.SHOPS_TCNAME, name);
		values.put(ShopsSQLiteHelper.SHOPS_TCCITY, city.getId());
		values.put(ShopsSQLiteHelper.SHOPS_TCLATITUDE, GPS.getLatitude());
		values.put(ShopsSQLiteHelper.SHOPS_TCLONGITUDE, GPS.getLongitude());
		values.put(ShopsSQLiteHelper.SHOPS_TCDESCRIPTION, description);
		long insertId = database.insert(ShopsSQLiteHelper.SHOPS_TABLE, null,
				values);

		 Cursor cursor = database.query(ShopsSQLiteHelper.SHOPS_TABLE,
		 allColumns, ShopsSQLiteHelper.SHOPS_TCID + " = " + insertId, null,
		 null, null, null);
		 cursor.moveToFirst();
		 
		 res = cursorToShop(cursor);
		 cursor.close();
		 close();
		 return res;
	}

	public void deleteShop(Shop shop) {
		open();
		
		long id = shop.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(ShopsSQLiteHelper.SHOPS_TABLE, ShopsSQLiteHelper.SHOPS_TCID
				+ " = " + id, null);
		
		close();
	}

	public List<Shop> getAllShops() {
		open();
		
		List<Shop> shops = new ArrayList<Shop>();
		Cursor cursor = database.query(ShopsSQLiteHelper.SHOPS_TABLE, allColumns,
				null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Shop shop = cursorToShop(cursor);
			shops.add(shop);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		
		close();
		return shops;
	}

	private Shop cursorToShop(Cursor cursor) {
		return new Shop(cursor.getLong(0), cursor.getString(1),
				cursor.getInt(2), cursor.getDouble(3), cursor.getDouble(4),
				cursor.getString(5));
	}
}
